import { Body, Controller, Post, Req } from '@nestjs/common';
import { BaseController } from '../base/base.controller';
import { DbService } from '@app/db';
import { PageDto } from './dto';
import { ChargeOrder } from '@app/db/entities/ChargeOrder';
import { And, FindOptionsWhere, In, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
import { User } from '@app/db/entities/User';
import { MongodbService } from '@app/mongodb';
import { DictionaryService } from '../common/dictionary/dictionary.service';

@Controller('chargeOrder')
export class ChargeOrderController extends BaseController{
    constructor(
        private readonly db:DbService,
        private readonly mongodb:MongodbService,
        private readonly dictionary:DictionaryService,
    ){
        super()
    }

    @Post('page')
    async page(@Body() dto:PageDto, @Req() { belong, memberId, member }) {

        let result:PaginationResult<ChargeOrder & {user? : User; stopReasonText?:string; failReasonText?:string}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<ChargeOrder> = {
            
        }

        if(belong == 1) {
            where.merchantId = member.tenantId
        }

        
        if(dto.orderNo) {
            where.orderNo = dto.orderNo
        }

        if(dto.startTime || dto.endTime) {
            if(dto.startTime == dto.endTime) {
                where.createTime = dto.startTime
            }else {
                const dates:any = []
                if(dto.startTime) {
                    dates.push(MoreThanOrEqual(dto.startTime))
                }

                if(dto.endTime) {
                    dates.push(LessThanOrEqual(dto.endTime))
                }

                where.createTime = And(...dates)
            }
        }

        result.total = await this.db.chargeOrder.count(where)

        if(result.total > 0) {
            result.rows = await this.db.chargeOrder.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})

            const userIds:number[] = []
            const userMap:{[key:string]:User} = {}

            if(result.rows.length > 0) {
                const reasons = await this.dictionary.getItemCodeToNameByCategory('CHARGE_STOP_REASON')
                const failReasons = await this.dictionary.getItemCodeToNameByCategory('CHARGE_FAIL_REASON')


                result.rows.forEach(row => {
                    if(!userIds.includes(row.userId)) {
                        userIds.push(row.userId)
                    }
                })

                let users = await this.db.user.find({id : userIds.length == 0 ? userIds[0] : In(userIds)}, ['id', 'nickname', 'avatar'])
                users.forEach(user => {
                    userMap[user.id] = user
                })
                users = null

                result.rows.forEach(row => {

                    if(row.status == 2 && reasons[row.stopReason] != undefined) {
                        row.stopReasonText = reasons[row.stopReason] as string
                    }

                    if(row.status == 3 && reasons[row.errorCode] != undefined) {
                        row.failReasonText = failReasons[row.errorCode] as string
                    }
                    

                    row.user = userMap[row.userId]
                })
            }

        }
        

        return this.successRes(result)

    }

    @Post('params')
    async params(@Body() dto:{id:number, pageNo:number, pageSize:number}) {
        const res = await this.mongodb.orderPowerData.findOne({orderId : dto.id}, {_id : 0, data : {$slice : ['$data', (dto.pageNo - 1) * dto.pageSize, dto.pageSize]}})
        return this.utils.successRes(res ? res.data : null)
    }
}
